<template>
  <view>
    <BottomView :page="page" v-if="needBottom" @open="open"></BottomView>
    <view v-if="showLogin" class="login-container">
      <view class="f1" @click="close('mask')"></view>
      <view class="login-panel flex-col">
        <image class="img-close" src="@/static/login/guanbi.png" @click="close('icon')"></image>
        <view class="title self-center">登录体验更多功能</view>
        <template v-if="step === 1">
          <view @tap="tryLogin('weixin')" v-if="hasWX" class="custom-btn weixin step1-main-btn">
            <image class="img-weixin" src="@/static/login/weixin_bai.png"/>
            <text>微信一键登录</text>
          </view>
          <view @tap="tryLogin('apple')" v-if="hasApple" class="custom-btn toutiao step1-main-btn">
            <image class="img-apple" src="@/static/login/pingguo.png"/>
            <text>苹果账号登录</text>
          </view>
          <view @tap="tryLogin('toutiao')" v-if="hasToutiao" class="custom-btn toutiao step1-main-btn">
            <image class="img-toutiao" src="@/static/login/toutiao.png"/>
            <text>抖音一键登录</text>
          </view>
          <view @click="step = 2" :class="['custom-btn phone step1-main-btn', hasPrimaryBtn?'':'primary']">手机号登录</view>
<!--          <view @click="univerifyLogin" :class="['custom-btn phone step1-main-btn', hasPrimaryBtn?'':'primary']">手机号登录</view>-->
        </template>
        <template v-else-if="step === 2">
          <view class="main-input-wrapper" style="margin-top: 0; margin-left: 56rpx; margin-right: 56rpx;">
            <input placeholder="请输入手机号" v-model="phone" maxlength="11" class="input"
                   type="number"
                   placeholder-class="placeholder"/>
          </view>
          <view class="main-input-wrapper"
                style="margin-bottom: 44rpx; margin-left: 56rpx; margin-right: 56rpx;">
            <input placeholder="请输入验证码" v-model="captcha" maxlength="4" class="input"
                   type="number"
                   placeholder-class="placeholder"/>
            <view class="divider"></view>
            <view :class="[time?'watting':'cando']" @click="toGetCaptcha">
              {{ time ? '重新获取 ' + time + 'S' : '获取验证码' }}
            </view>
          </view>
          <view @click="tryLogin('phone')" class="custom-btn primary-btn-green">登录</view>
        </template>
        <view class="flex-row align-center self-center" style="margin-bottom: 80rpx;" v-if="showProtocol">
          <radio :checked="agree" @click="agree=!agree" color="#3073f6" style="transform:scale(0.7)"/>
          <view class="flex-row tip-title">
            我已阅读并同意
            <view class="href" @click="toYonghu">《用户协议》</view>
            和
            <view class="href" @click="toYinsi">《隐私政策》</view>
          </view>
        </view>
        <view v-else style="margin-bottom: 80rpx;"></view>
        <view class="row self-center" v-if="showThird" style="margin-bottom: 80rpx;">
          <view @click="tryLogin('weixin')" class="custom-btn footer-third-btn wx"
                v-if="hasWX && step === 2">
            <image class="img-weixin" src="@/static/login/weixin.png"/>
            微信登录
          </view>
          <view @click="tryLogin('toutiao')" class="custom-btn footer-third-btn toutiao"
                v-if="hasToutiao && step === 2">
            <image class="img-toutiao" src="@/static/login/toutiao.png"/>
            抖音登录
          </view>
          <image @click="tryLogin('apple')" v-if="hasApple" class="footer-third-btn apple"
                 src="@/static/login/pingguo.png"></image>
        </view>
      </view>
      <AgreementDialog ref="agreementdialog"></AgreementDialog>
      <MergeAccountDialog ref="mergeDialog"></MergeAccountDialog>
    </view>

    <QuickLoginDialog ref="quickLoginDialog" @quick="open"></QuickLoginDialog>
  </view>
</template>

<script>
import {mapActions, mapGetters} from 'vuex'
import {commonApi} from "@/api";
import MergeAccountDialog from '@/components/LoginView/MergeAccountDialog'
import AgreementDialog from '@/components/LoginView/AgreementDialog'
import QuickLoginDialog from '@/components/LoginView/QuickLoginDialog'
import BottomView from "@/components/LoginView/BottomView";
import utils from "../../libs/utils";
import appConfig from "@/appConfig";

export default {
  name: "LoginView",
  props: ['needBottom', 'page'],
  components: {
    BottomView,
    MergeAccountDialog,
    AgreementDialog,
    QuickLoginDialog
  },
  data() {
    return {
      agree: false,
      hasWX: false,
      hasToutiao: false,
      hasApple: false,
      showProtocol: true,
      phone: '',
      captcha: '',
      time: 0,
      showBottom: true,
      step: 1,
      loginInfo: null,
      showLogin: false,
      actionTabBar: false
    };
  },
  computed: {
    ...mapGetters(['platform', 'systemInfo']),
    hasPrimaryBtn() {
      return this.hasWX || this.hasToutiao
    },
    showThird() {
      if (this.step === 1) {
        return false
      }

      return this.hasToutiao || this.hasWX || this.hasApple
    }
  },
  created() {
    uni.showTabBar();
    uni.getProvider({
      service: 'oauth',
      success: (res) => {
        res.provider.map(item => {
          if (item === 'weixin') {
            this.hasWX = true
          } else if (item === 'apple') {
            this.hasApple = true
          } else if (item === 'toutiao') {
            this.hasToutiao = true
          }
        })
      }
    })

    if (this.platform === 'ios') {
      this.hasApple = true
    }
  },
  methods: {
    ...mapActions(['login']),
    ...mapActions('question', ['initUserData']),
    open() {
      this.step = 1;
      this.agree = false

      // #ifdef APP-PLUS
      // return this.univerifyLogin()
      // #endif
      this.showLogin = true;

      // #ifdef MP-TOUTIAO
      this.showProtocol = false
      this.agree = true
      // #endif
    },
    openQuickLoginDialog(closeCB) {
      this.$refs.quickLoginDialog.open(closeCB)
    },
    close(from) {
      this.$emit('close')
      this.closeTimeDown()
      this.showLogin = false;
    },
    toYinsi() {
      uni.navigateTo({
        url: '/pages/webview/webview?type=yinsi'
      });
    },
    toYonghu() {
      uni.navigateTo({
        url: '/pages/webview/webview?type=yonghu',
      });
    },
    univerifyLogin() {
      const univerifyManager = uni.getUniverifyManager()
      univerifyManager.login({
        univerifyStyle: {
          "fullScreen": true,
        },
        success(res) {
          console.log('login success', res)
        },
        fail(res) {
          console.log(res.errCode)
          console.log(res.errMsg)
        }
      })

      // univerifyManager.login({
      //   univerifyStyle: {
      //     "fullScreen": false,
      //     // "buttons": {
      //     //   "iconWidth": "45px",
      //     //   "list": [
      //     //     {
      //     //       "provider": "apple",
      //     //       "iconPath": "/static/login/pingguo.png"
      //     //     },
      //     //     {
      //     //       "provider": "weixin",
      //     //       "iconPath": "/static/login/weixin.png"
      //     //     }
      //     //   ]
      //     // }
      //     "authButton": {
      //       "normalColor": "#3479f5", // 授权按钮正常状态背景颜色 默认值：#3479f5
      //       "highlightColor": "#2861c5",  // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
      //       "disabledColor": "#73aaf5",  // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
      //       "textColor": "#ffffff",  // 授权按钮文字颜色 默认值：#ffffff
      //       "title": "本机号码一键登录", // 授权按钮文案 默认值：“本机号码一键登录”
      //       "borderRadius": "24px"	// 授权按钮圆角 默认值："24px" （按钮高度的一半）
      //     },
      //     // "otherLoginButton": {
      //     //   "normalColor": "#1dad52", // 授权按钮正常状态背景颜色 默认值：#3479f5
      //     //   "highlightColor": "#1dad52",  // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
      //     //   "disabledColor": "#60d98d",  // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
      //     //   "textColor": "#ffffff",  // 授权按钮文字颜色 默认值：#ffffff
      //     //   "title": "微信登录", // 授权按钮文案 默认值：“本机号码一键登录”
      //     //   "borderRadius": "24px"	// 授权按钮圆角 默认值："24px" （按钮高度的一半）
      //     // },
      //     "privacyTerms": {
      //       "defaultCheckBoxState": true, // 条款勾选框初始状态 默认值： true
      //       "isCenterHint": false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
      //       "uncheckedImage": "", // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)
      //       "checkedImage": "", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
      //       "checkBoxSize": 14, // 可选 条款勾选框大小
      //       "textColor": "#BBBBBB", // 文字颜色 默认值：#BBBBBB
      //       "termsColor": "#5496E3", //  协议文字颜色 默认值： #5496E3
      //       "prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”
      //       "suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
      //       "privacyItems": [  // 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效
      //         {
      //           "url": appConfig.host + appConfig.h5.yonghu, // 点击跳转的协议详情页面
      //           "title": "用户协议" // 协议名称
      //         },
      //         {
      //           "url": appConfig.host + appConfig.h5.yinsi, // 点击跳转的协议详情页面
      //           "title": "隐私协议" // 协议名称
      //         }
      //       ]
      //     },
      //   },
      //   success: async (res) => {  //预登录成功
      //     // 显示一键登录选项
      //     // const res2 = await uniCloud.callFunction({
      //     //   name: 'xxx',
      //     //   data: res.authResult
      //     // })
      //     // console.log('success', res, res2)
      //     // if (res2.result.success) {
      //     //   this.phone = res2.result.phoneNumber
      //     //   await this.tryLogin('univerify')
      //     // } else {
      //     //   uni.showToast({
      //     //     title: res2.result.errMsg
      //     //   })
      //     // }
      //     // uni.closeAuthView()
      //   },
      //   fail: (res) => {  // 预登录失败
      //     // 不显示一键登录选项（或置灰）
      //     // 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
      //     console.log('fail', res)
      //     // univerifyManager.getCheckBoxState({
      //     //   success: (res2) => {
      //     //     console.log("getCheckBoxState res: ", res2);
      //     //     if (res.errCode === 30002) {
      //     //       this.showLogin = true;
      //     //     }
      //     //
      //     //     if (res2.state) {
      //     //       // 关闭一键登录弹框
      //     //       this.agree = res2.state
      //     //     }
      //     //     // univerifyManager.close()
      //     //   }
      //     // })
      //   }
      // })
    },
    async tryLogin(provider) {
      if (this._locked) {
        console.log('lock tryLogin')
        return
      }

      this._locked = true

      try {
        // #ifdef H5
        // if (provider === 'phone') {
        //   provider = 'admin'
        // }
        // #endif
        if (provider === 'phone') {
          if (!this.phone || !this.captcha) {
            throw new Error('请输入手机号和验证码')
          }
          if (!this.checkPhone(this.phone)) {
            throw new Error('请输入有效手机号')
          }
          if (this.captcha.length !== 4) {
            throw new Error('验证码有效长度为4')
          }
        }
        let user, platform = provider
        // #ifdef MP-TOUTIAO
        const userRes = await this.uniGetUserProfile()
        user = userRes.userInfo
        platform = 'toutiao_xcx'
        // #endif
        console.log('this.agree', this.agree)
        if (!this.agree && provider !== 'univerify') {
          await this.$refs.agreementdialog.open()
          this.agree = true
        }
        // #ifdef MP-WEIXIN
        platform = 'weixin_xcx'
        // #endif
        const useNew = await this.checkUserIsExist(provider, platform, user)
        await this.mergeUser(useNew)

      } catch (e) {
        console.log(e)
        if (e && e.message)
          uni.showToast({
            title: e.message,
            icon: 'none',
            duration: 2000
          });
      }
      this._locked = false
    },
    async mergeUser(useNew) {
      uni.showLoading({
        title: '加载中...',
      })
      try {
        const result = await this.login({
          useNew,
          ...this.loginInfo
        })
        this.close('finish')
        await this.initUserData()
        this.$emit('login_success')
        if (result) {
          uni.navigateTo({
            url: '/pages/vip/vip?tipShow=' + result
          })
        }
      } catch (e) {
        throw e
      }

      uni.hideLoading()
    },
    async checkUserIsExist(provider, platform, user) {
      // console.log('checkUserIsExist', platform, utils.encrypt(this.phone))
      uni.showLoading({
        title: '加载中...',
      })
      if (provider === 'phone') {
        this.loginInfo = {
          provider,
          authResult: {
            phone: this.phone,
            captcha: this.captcha,
          }
        }
      } else if (provider === 'admin') {
        this.loginInfo = {
          provider,
          authResult: {
            phone: this.phone,
            captcha: this.captcha,
          }
        }
      } else if (provider === 'password') {
        this.loginInfo = {
          provider,
          authResult: {
            phone: this.phone,
            password: this.captcha,
          }
        }
      } else if (provider === 'univerify') {
        this.loginInfo = {
          provider,
          authResult: {
            phone: utils.encrypt(this.phone),
          }
        }
      } else {
        const loginRes = await utils.uniLogin(provider)
        let authResult = loginRes.authResult || {};
        if (provider === 'apple') {
          authResult = loginRes.appleInfo;
        }

        authResult.anonymousCode = loginRes.anonymousCode
        authResult.code = loginRes.code
        this.loginInfo = {
          provider: platform,
          authResult,
          user
        }
      }
      const res = await commonApi.checkUserIsExist(this.loginInfo)
      uni.hideLoading()
      let {isExist, useNew, userSysInfo} = res.data.data;
      if (isExist && useNew === -1) {
        useNew = await this.$refs.mergeDialog.open(userSysInfo)
      }

      return useNew
    },

    uniGetUserProfile() {
      return new Promise((resolve, reject) => {
        // todo 兼容头条sdk 2.53.0
        /**
         * getUserProfile必须先调用Login，但是调用login后无法调用getUserProfile(原因：本方法必须tap触发)
         */
        uni.getUserProfile({
          desc: '用于注册信息',
          success: resolve,
          fail: reject
        })
      })
    },

    async toGetCaptcha() {
      if (this.time || !this.phone) {
        return
      }
      if (!this.checkPhone(this.phone)) {
        uni.showToast({
          title: '请输入有效的手机号',
          icon: 'none',
          duration: 2000
        });
        return
      }
      uni.showLoading({
        title: '加载中...',
      })
      try {
        // console.log("hsf", "phone:" + this.phone)
        const res = await commonApi.getCaptcha(this.phone)

        this.time = 60

        this._handler = setInterval(() => {
          if (this.time > 0) {
            this.time--
            // console.log("hsf", "time:" + this.time)
          } else {
            clearInterval(this._handler)
            this._handler = null
          }
        }, 1000)
      } catch (e) {
        if (e && e.message)
          uni.showToast({
            title: e.message,
            icon: 'none',
            duration: 2000
          });
      }
      uni.hideLoading()
    },
    closeTimeDown() {
      if (this._handler) {
        clearInterval(this._handler)
        this._handler = null
        this.time = 0
      }
    },
    checkPhone(phone) {
      console.log('phone', phone)
      if (!phone || !(/^1\d{10}$/.test(phone))) {
        return false;
      }
      return true;
    },
  }
}
</script>

<style lang="scss">

.login-container {
  z-index: 100;
  background-color: rgba(0, 0, 0, 0.85);
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;

  .login-panel {
    background-color: #fff;
    border-top-left-radius: 28rpx;
    border-top-right-radius: 28rpx;
    width: 100%;
    position: relative;

    .img-close {
      position: absolute;
      top: 48rpx;
      right: 48rpx;
      width: 26rpx;
      height: 26rpx;
    }

    .title {
      color: #090909;
      font-size: 36rpx;
      margin-top: 64rpx;
      margin-bottom: 60rpx;
    }

    .step1-main-btn {
      margin-left: 64rpx;
      margin-right: 64rpx;
      margin-bottom: 36rpx;
      font-size: 32rpx;
      color: #fff;

      &.weixin {
        background-color: #00E06B;
      }

      &.toutiao {
        background-color: #020202;
      }

      &.phone {
        background-color: #d5d5d5;
        color: #555;
      }

      &.primary {
        background-color: #3073F6;
        color: #fff;
      }
    }


    .primary-btn-green {
      margin-left: 56rpx;
      margin-right: 56rpx;
      margin-bottom: 36rpx;
      font-size: 32rpx;
      background-color: #3073F6;
      color: #fff;
    }

    .img-weixin {
      width: 38rpx;
      height: 32rpx;
      margin-right: 12rpx;
    }

    .img-apple {
      width: 74rpx;
      height: 74rpx;
      margin-left: -15px;
      margin-right: 0rpx;
    }

    .img-toutiao {
      width: 34rpx;
      height: 44rpx;
      margin-right: 12rpx;
    }

    .tip-title {
      font-size: 26rpx;
      color: #515151;

      .href {
        color: #3073F6;
      }
    }

    .placeholder {
      font-size: 28rpx;
      color: #989898;
    }

    .input {
      font-size: 32rpx;
      color: #000;
    }

    .divider {
      background-color: #ddd;
      width: 1px;
      height: 60rpx;
      margin-right: 36rpx;
    }

    .watting {
      font-size: 26rpx;
      color: #C5C5C5;
    }

    .cando {
      font-size: 26rpx;
      color: #3073F6;
    }
  }


  .footer-third-btn {
    margin-left: 80rpx;

    &.wx {
      color: #00E06B;
      font-size: 28rpx;
      width: 246rpx;
      height: 76rpx;
      background-color: #F1F4FB;
    }

    &.apple {
      width: 74rpx;
      height: 74rpx;
    }

    &.toutiao {
      color: #fff;
      font-size: 28rpx;
      width: 246rpx;
      height: 76rpx;
      background-color: #0C0C18;
    }

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
